<!-- 查询条件 -->
<template>
  <el-form
    :inline="true"
    :model="searchParam"
    ref="searchParam"
    :label-width="labelWidth"
    class="padding-15 oa_form_max search_form_o_max"
  >
    <!-- 循环生成表单填写项 -->
    <template v-for="(item, i) in fields">
      <el-form-item :label="item.label" :key="i">
        <!-- 下拉类型 -->
        <el-select
          clearable
          @clear="searchList"
          v-if="item.type === 'select'"
          v-model="searchParam[item.key]"
          @change="
            (value) => {
              searchChange(value, item.key)
            }
          "
        >
          <el-option
            v-for="(subItem, sonIndex) in item.options.list"
            :key="sonIndex"
            :label="subItem.label"
            :value="subItem.value"
          />
        </el-select>
        <!-- 下拉树形数据 -->
        <el-select
          clearable
          @clear="searchList"
          v-if="item.type === 'selectTree'"
          v-model="searchParam[item.key]"
          @change="
            (value) => {
              searchChange(value, item.key)
            }
          "
        >
          <el-option hidden key="id" :value="value" :label="label"></el-option>
          <el-tree
            node-key="id"
            class="elTree"
            :data="item.options.list"
            :props="{ children: 'children', label: 'name' }"
            :expand-on-click-node="false"
            default-expand-all
            @node-click="
              (e) => {
                clicktree(e, item.key)
              }
            "
          ></el-tree>
        </el-select>
        <!-- 单选 -->
        <template v-else-if="item.type === 'radio'">
          <el-radio-group v-model="searchParam[item.key]">
            <el-radio v-for="(subItem, index) in item.options.list" :key="index" :label="subItem.value">{{
              subItem.label
            }}</el-radio>
          </el-radio-group>
        </template>
        <!-- 多选 -->
        <template v-else-if="item.type === 'checkbox'">
          <el-checkbox-group v-model="searchParam[item.key]">
            <el-checkbox v-for="(subItem, index) in item.options.list" :key="index" :label="subItem.value">{{
              subItem.label
            }}</el-checkbox>
          </el-checkbox-group>
        </template>
        <!-- 时间选择 -->
        <template v-else-if="/^date-/.test(item.type)">
          <el-date-picker
            v-model="searchParam[item.key]"
            type="date"
            :placeholder="item.placeholder"
            :editable="false"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </template>
        <!-- 时间范围选择 -->
        <template v-else-if="item.type == 'datetimerange'">
          <el-date-picker
            v-model="searchParam[item.key]"
            @change="datetimerangeChange($event, item.key)"
            type="datetimerange"
            class="search_time"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </template>
        <!-- 输入框范围选择 -->
        <template v-else-if="item.type == 'scopeInput'">
          <div class="scopeInput">
            <el-input
              clearable
              :type="item.type"
              v-model="searchParam[item.key.split('-')[0]]"
              @input="changeInput(item.key)"
            ></el-input>
            <span style="color: #ccc">～</span>
            <el-input
              clearable
              :type="item.type"
              v-model="searchParam[item.key.split('-')[1]]"
              @input="changeInput(item.key)"
            ></el-input>
          </div>
        </template>
        <!-- 数字输入框 -->
        <template v-else-if="item.type === 'number'">
          <el-input
            clearable
            type="number"
            :class="item.isTitle ? 'form_title' : ''"
            v-model="searchParam[item.key]"
          ></el-input>
        </template>
        <!-- 输入框 -->
        <template v-else-if="item.type === 'input' || item.type === 'textarea'">
          <el-input
            :type="item.type"
            :class="item.isTitle ? 'form_title' : ''"
            v-model="searchParam[item.key]"
            @clear="searchList"
            clearable
          ></el-input>
        </template>
      </el-form-item>
    </template>
    <slot />
    <div class="search_foot_but jac">
      <el-button type="primary" size="mini" @click="searchList">检索</el-button>
      <el-button size="mini" @click="resetHandle">重置</el-button>
      <slot name="foot_but"></slot>
    </div>
  </el-form>
</template>

<script>
export default {
  name: 'FueryForm',
  props: {
    // 左侧宽度
    labelWidth: {
      type: String,
      default: '90px'
    },
    // 输入框对应表
    fields: {
      type: Array,
      default: () => [
        { key: 'title', label: '标题:', type: 'input', isTitle: true },
        { key: 'startDate', label: '开始日期:', type: 'date-s' },
        { key: 'endDate', label: '结束日期:', type: 'date-e' }
      ]
    }
  },
  data() {
    return {
      searchParam: {},
      value: '',
      label: '',
      inputKey: ''
    }
  },
  watch: {
    fields() {
      this.initForm()
    }
  },
  created() {
    // 初始化表单
    this.initForm()
  },
  //方法集合
  methods: {
    searchChange(data, key) {
      this.$emit('selectsearchChange', [key, data])
    },
    //范围校验
    changeInput(key) {
      this.inputKey = key
    },
    // 初始化搜索表单
    initForm() {
      for (let item of this.fields) {
        if (item.type == 'datetimerange') {
          this.$set(this.searchParam, item.key, item.defaultValue || [])
        } else {
          this.$set(this.searchParam, item.key, item.defaultValue || '')
        }
        if (item.type == 'scopeInput') {
          this.$set(this.searchParam, item.key.split('-')[0], item.defaultValue || '')
          this.$set(this.searchParam, item.key.split('-')[1], item.defaultValue || '')
        }
      }
    },
    // 搜索列表
    searchList() {
      // 单个时间选择验证
      let isItemDate = this.fields.find((item) => /^date-/.test(item.type))
      if (isItemDate && !this.redioDateVali()) {
        return
      }
      //输入框范围校验
      let str = this.fields.filter((item) => item['key'] == this.inputKey)
      let rule = this.inputKey.split('-')
      if (this.searchParam[rule[0]] && this.searchParam[rule[1]]) {
        if (+this.searchParam[rule[0]] > +this.searchParam[rule[1]]) {
          return this.$message.error(`开始${str[0].label}不能大于结束${str[0].label}`)
        } else {
          this.$emit('searchList', this.getSearchParams())
        }
      } else {
        this.$emit('searchList', this.getSearchParams())
      }
    },
    // 重置搜索参数
    resetHandle() {
      this.$emit('resetHandle')
      this.initForm()
      this.searchList()
    },
    // 获取查询参数
    getSearchParams() {
      let s = this.searchParam
      let params = {}
      for (let key in s) {
        if (s[key] === undefined || s[key] === '') continue
        let item = this.fields.find((e) => {
          if (e.key == key || e.key == this.inputKey) {
            return true
          }
        })
        if (!item) continue
        // 时间范围选择单独处理

        if (item.type == 'datetimerange') {
          if (s[key].length) {
            params[key.split('-')[0]] = s[key][0]
            params[key.split('-')[1]] = s[key][1]
          }
        } else {
          params[key] = s[key]
        }
      }
      return params
    },
    // 两侧时间选择验证
    redioDateVali() {
      let sKey = this.fields.find((e) => e.type == 'date-s')
      let eKey = this.fields.find((e) => e.type == 'date-e')
      let startDate = sKey ? this.searchParam[sKey.key] : ''
      let endDate = eKey ? this.searchParam[eKey.key] : ''
      if (startDate && !endDate) {
        this.$notify.error('请选择结束时间')
        return false
      }
      if (!startDate && endDate) {
        this.$notify.error('请选择开始时间')
        return false
      }
      if (startDate > endDate) {
        this.$notify.error('开始时间不得大于结束时间')
        return false
      }
      return true
    },
    //下拉树形数据
    clicktree(event, key) {
      // console.log(event, searchParam);
      this.searchParam[key] = event.id
      this.value = event.id
      this.label = event.name
    },
    // 时间范围选择同一天处理
    datetimerangeChange(time, key) {
      let [s, e] = time
      if (s == e) {
        e = e.replace('00:00:00', '23:59:59')
      }
      this.searchParam[key] = [s, e]
    }
  }
}
</script>
<style lang="scss" scoped>
v-deep.el-form--inline {
  .el-form-item__label {
    float: inline-end !important;
  }
}
.scopeInput {
  display: flex;
}

$h: 22px;
.search_time {
  width: 546px !important;
  ::v-deep .el-range__icon {
    line-height: $h;
  }
  ::v-deep .el-range-separator {
    line-height: $h;
  }
  ::v-deep .el-range__close-icon {
    line-height: $h;
  }
}

.el-form-item {
  ::v-deep.el-form-item__content {
    .el-select {
      line-height: 30px !important;
      height: 30px !important;
    }
  }
}
.padding-15 {
  padding: 15px;
}
</style>
